<?php
// 开启会话
session_start();

// 初始化游戏数据
if (!isset($_SESSION['seeds'])) {
    $_SESSION['seeds'] = 5; // 初始种子数量
    $_SESSION['field'] = [
        'planted' => false, // 菜地是否已播种
        'growth' => 0,      // 作物生长进度（0 - 100）
        'harvested' => false // 作物是否已收获
    ];
}

// 处理用户操作
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['plant'])) {
        if ($_SESSION['seeds'] > 0 && !$_SESSION['field']['planted']) {
            $_SESSION['seeds']--;
            $_SESSION['field']['planted'] = true;
            $_SESSION['field']['growth'] = 0;
            $_SESSION['field']['harvested'] = false;
        }
    } elseif (isset($_POST['water'])) {
        if ($_SESSION['field']['planted'] && !$_SESSION['field']['harvested']) {
            $_SESSION['field']['growth'] += 20;
            if ($_SESSION['field']['growth'] >= 100) {
                $_SESSION['field']['growth'] = 100;
            }
        }
    } elseif (isset($_POST['harvest'])) {
        if ($_SESSION['field']['planted'] && $_SESSION['field']['growth'] >= 100 && !$_SESSION['field']['harvested']) {
            $_SESSION['seeds'] += 3; // 收获后获得 3 颗种子
            $_SESSION['field']['planted'] = false;
            $_SESSION['field']['growth'] = 0;
            $_SESSION['field']['harvested'] = true;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>种菜网页游戏</title>
</head>

<body>
    <h1>种菜网页游戏</h1>
    <p>种子数量: <?php echo $_SESSION['seeds']; ?></p>
    <p>菜地状态: 
        <?php
        if ($_SESSION['field']['planted']) {
            if ($_SESSION['field']['growth'] < 100) {
                echo "已播种，生长进度: " . $_SESSION['field']['growth'] . "%";
            } else {
                echo "作物已成熟，可以收获";
            }
        } else {
            echo "未播种";
        }
        ?>
    </p>

    <form method="post">
        <?php if ($_SESSION['seeds'] > 0 && !$_SESSION['field']['planted']): ?>
            <input type="submit" name="plant" value="播种">
        <?php endif; ?>
        <?php if ($_SESSION['field']['planted'] && !$_SESSION['field']['harvested']): ?>
            <input type="submit" name="water" value="浇水">
        <?php endif; ?>
        <?php if ($_SESSION['field']['planted'] && $_SESSION['field']['growth'] >= 100 && !$_SESSION['field']['harvested']): ?>
            <input type="submit" name="harvest" value="收获">
        <?php endif; ?>
    </form>
</body>

</html>